package org.radar.vm;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

/**
 * 虚拟机信息工具类
 *
 * @author zhangcs
 * @since 1.0
 */
public class VmTool {

    /**
     * 获取所有线程
     *
     * @return 返回当前进程所有线程数组
     */
    private static synchronized native Thread[] getAllThreads();

    private static VmTool instance;

    private VmTool() {
    }

    /**
     * 获取VM工具类实例
     *
     * @return 返回VM工具对象
     */
    public static VmTool getInstance() {
        return getInstance(null);
    }

    /**
     * 获取VM工具类实例
     *
     * @param libPath library文件路径，该参数为{@code null}时使用系统默认路径
     * @return 返回VM工具对象
     */
    public static VmTool getInstance(String libPath) {
        if (instance != null) {
            return instance;
        }

        if (libPath == null) {
            System.loadLibrary(VmToolUtils.JNI_LIBRARY_NAME);
        } else {
            System.load(libPath);
        }

        instance = new VmTool();
        return instance;
    }

    public long[] getThreads() {
        ThreadMXBean bean = ManagementFactory.getThreadMXBean();
        long[] threadIds = bean.getAllThreadIds();
        return threadIds;
    }

}
